# Python 2.4 compatibility
try:
    import json
except ImportError:
    import simplejson as json
    
from django.http import HttpResponse

from chat.model.Channel import Channel
from chat.model.PrivateChannel import PrivateChannel
from chat.model.User import User

from chat.views.action.ActionFactory import ActionFactory
from chat.views.action.Response import serialize_response_data

from action.ActionExceptions import *

def action(request):
        
    if request.is_ajax() and request.method == 'POST':
        # Get the handler for the requested action
        handler = ActionFactory.get_instance(request.POST.get('action', None))
        handler.set_request(request)
        if handler is None:
            return HttpResponse(status=500)

        # Handle the requested action
        try:
            User.prune_users()
            Channel.prune_channels()
            PrivateChannel.prune_channels()
            
            return HttpResponse(serialize_response(handler.handle(request.POST)), 'application/json')
        except ActionIntegrityException:
            return HttpResponse(status=400)
        except TargetException:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)

def serialize_response(response):
    response_json = response.get_json()
    return json.dumps(response_json, default=serialize_response_data)


